<template>
    <el-dialog
        title="新增诊改报告"
        :close-on-click-modal="false"
        :visible.sync="reportDialogParams.visible"
        width="30%"
        @close="close('formData')"
    >
        <el-form
            ref="formData"
            :rules="rules"
            :model="formData"
            label-width="120px"
        >
            <!-- $route.params.type == 'BG_ZT' -->
            <el-form-item label="所属诊改阶段" prop="year">
                <el-select
                    v-model="formData.year"
                    placeholder="请选择所属诊改阶段"
                    @change="changeYear"
                >
                    <el-option
                        v-for="year in yearArr"
                        :key="year"
                        :label="`${year}年`"
                        :value="year"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="报告名称" prop="reportName">
                <!-- <el-input type="text" placeholder="请输入报告名称" v-model="formData.reportName"></el-input> -->
                <el-select
                    v-model="formData.reportName"
                    placeholder="请选择报告名称"
                    @change="changeChainObj"
                >
                    <el-option
                        v-for="(item, i) in reportNameOptions"
                        :key="i"
                        :label="item.reportName"
                        :value="item.id"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item
                v-if="
                    $route.params.type == 'BG_LEVEL_JS' ||
                        $route.params.type == 'BG_LEVEL_XS'
                "
                label="所属学院"
                prop="belongSchool"
            >
                <el-select
                    v-model="formData.belongSchool"
                    filterable
                    placeholder="请选择所属学院"
                >
                    <el-option
                        :label="item.college"
                        :value="item.id"
                        v-for="(item, i) in schoolArr"
                        :key="i"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item
                :label="belongDepartment($route.params.type)"
                prop="deptCode"
            >
                <el-select
                    v-model="formData.deptCode"
                    filterable
                    :placeholder="
                        `请选择${belongDepartment($route.params.type)}`
                    "
                    @change="changeDept"
                >
                    <el-option
                        :label="item.orgName"
                        :value="
                            $route.params.type != 'BG_LEVEL_KC'
                                ? item.orgCode
                                : item.id
                        "
                        v-for="(item, i) in organizeArr"
                        :key="i"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="填写人员" prop="username">
                <el-select
                    filterable
                    v-model="formData.username"
                    multiple
                    placeholder="请选择填写人员"
                >
                    <el-option
                        :label="item.realName"
                        :value="item.userName"
                        v-for="(item, i) in peopleArr"
                        :key="i"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="关联目标标准" prop="id">
                <el-select
                    v-model="formData.id"
                    multiple
                    placeholder="请选择目标标准"
                >
                    <el-option
                        v-for="(item, i) in targetStandardArr"
                        :key="i"
                        :label="item.name"
                        :value="item.id"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="close('formData')">关 闭</el-button>
            <el-button type="primary" @click="submit('formData')"
                >保 存</el-button
            >
        </span>
    </el-dialog>
</template>

<script>
import {
    getAllOrganize,
    queryByCode,
    getUserByDept,
    getAdminAndChargeByOrgId
} from '@/api/systemManage';
import { getQueryTarget } from '@/api/target';
import {
    createReport,
    getReportNameById,
    getProfessionalById,
    getCourseReportNameById,
    getCourseSpecializedReportNameById
} from '@/api/report';
import { getStorage } from '../../../../config/utils';
export default {
    name: 'createReportDialog',
    props: {
        reportDialogParams: {
            type: Object
        }
    },
    data () {
        return {
            targetStandardArr: [],
            // tempTargetStandardArr: [],
            peopleArr: [],
            organizeArr: [],
            formData: {
                reportName: '',
                year: '',
                deptCode: '',
                username: [],
                id: [],
                adminId: '',
                dutyPart: '',
                // 所属学院
                belongSchool: ''
                // auditDept: ''
            },
            reportNameOptions: [],
            rules: {
                val: [
                    { required: true, message: '请输入校准值', trigger: 'blur' }
                ]
            },
            levelType: '',
            userInfo: getStorage('userInfo'),
            // 本部门参与人
            deptUserArr: [],
            // 报告最终名称
            lastName: '',
            // 当前层级页面
            reportType: '',
            // 所属学院组
            schoolArr: [],
            reportCode: ''
        };
    },
    computed: {
        yearArr () {
            return this.$config.yearArr();
        }
        // 专业层诊改报告获取审核部门
        /* auditDeptArr () {
            return this.organizeArr.filter(item => {
                // 二级学院
                if (this.$route.params.type === 'BG_LEVEL_ZY') {
                    return item.orgType === '1';
                }

                // 3班级
                if (this.$route.params.type === 'BG_LEVEL_XS') {
                    return item.orgType === '3';
                }
            });
        } */
    },
    watch: {
        // $route (to, from) {
        //     console.log(to, from);
        // }
    },
    created () {
        // console.log(this.reportType, 'dialog currentPageName');
        // this.changeDept(getStorage('userInfo').orgCode)
        // console.log(this.$route.query.name, 'slkdjflsjdf');
    },
    mounted () {
        this.getProfessional();
        if (!['BG_LEVEL_KC'].includes(this.$route.params.type)) {
            this.formData.deptCode = getStorage('userInfo').orgCode;
            this.getOrganize();
        }
        this.changeYear();
    },
    methods: {
        getProfessional () {
            getProfessionalById().then(res => {
                // console.log(res, 'getProfessionalById');
                res.map(item => {
                    item.orgName = item.splicing;
                });
                this.organizeArr = res;
                this.schoolArr = res;
                this.formData.belongSchool = res[0]?.id;
                if (this.$route.params.type !== 'BG_LEVEL_KC') {
                    this.formData.deptCode = res[0]?.orgCode;
                }
                if (this.$route.params.type !== 'BG_LEVEL_KC') {
                    this.changeDept(this.formData.deptCode);
                }
            });
        },
        submit (formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    let dept;
                    if (this.$route.params.type !== 'BG_LEVEL_KC') {
                        dept = this.organizeArr.find(item => {
                            return item.orgCode === this.formData.deptCode;
                        });
                    }
                    const preparationPaticipant = [];
                    for (const element in this.formData.username) {
                        const preparation = {};
                        const obj = this.peopleArr.find(item => {
                            return (
                                item.userName ===
                                this.formData.username[element]
                            );
                        });
                        preparation.realName = obj.realName;
                        preparation.userId = parseInt(obj.id);
                        preparationPaticipant.push(preparation);
                    }
                    this.reportNameOptions.map(child => {
                        if (this.formData.reportName === child.id) {
                            this.lastName = child.reportName;
                        }
                    });

                    const params = {
                        reportIndex: this.$route.params.type,
                        reportName: this.lastName,
                        reportYear: this.formData.year,
                        // 所属部门
                        preparationDepartment:
                            this.$route.params.type !== 'BG_LEVEL_KC'
                                ? dept.id
                                : this.organizeArr[0].orgId,
                        preparationPaticipant: preparationPaticipant,
                        targetStandardId: this.formData.id.toString(),
                        // 审核人Id
                        examineUser: this.formData.adminId,
                        reportCode: this.reportCode
                    };

                    // 如果审核人为空（不需要审核）传当前登录人的Id
                    if (params.examineUser == '') {
                        params.examineUser = getStorage('userInfo').id;
                    }

                    createReport(params).then(res => {
                        this.$message.success('新增成功！');
                        this.reportDialogParams.visible = false;
                        this.$emit('getList');
                    });
                } else {
                    return false;
                }
            });
        },
        // 关闭
        close (formName) {
            this.$refs[formName].resetFields();
            this.reportNameOptions = [];
            this.reportDialogParams.visible = false;
        },
        getOrganize () {
            getAllOrganize()
                .then(res => {
                    this.organizeArr = res || [];
                })
                .catch();
        },
        // 获得关联目标标准
        changeChainObj (val) {
            if (['BG_LEVEL_KC'].includes(this.$route.params.type)) {
                this.formData.deptCode = val;
                // console.log(this.formData.deptCode);
                this.changeDept(val);
            }
            if (!['BG_ZT'].includes(this.$route.params.type)) {
                // console.log(val, 'val,item');
                this.formData.id = [];
                this.targetStandardArr.map(item => {
                    this.reportNameOptions.map(v => {
                        if (item.reportCode === v.reportCode && val === v.id) {
                            this.formData.id.push(item.id);
                            this.reportCode = item.reportCode;
                        }
                    });
                });
            }
        },
        changeYear () {
            if (this.formData.year) {
                const params = {
                    reportIndex: this.$route.params.type,
                    year: this.formData.year,
                    id: getStorage('userInfo').id
                };
                if (['BG_LEVEL_KC'].includes(this.$route.params.type)) {
                    getCourseReportNameById(params).then(res => {
                        console.log(res, 'getCourseReportNameById');
                        this.reportNameOptions = res;
                    });
                    // getCourseSpecializedReportNameById(params).then(res => {
                    //     // console.log(res, 'getCourseSpecializedReportNameById');
                    //     this.organizeArr = res;
                    // });
                }
                if (!['BG_LEVEL_KC'].includes(this.$route.params.type)) {
                    getReportNameById(params).then(res => {
                        // console.log(res, '-=str');
                        if (res) {
                            this.reportNameOptions = res;
                        }
                    });
                    getQueryTarget(params).then(res => {
                        if (res) {
                            this.targetStandardArr = res;
                            // console.log('currentPageName', this.targetStandardArr);
                            // this.tempTargetStandardArr = this.targetStandardArr;reportCode
                        }
                    });
                }
            }
        },
        changeDept (code) {
            // console.log(code, 'code', this.$route.params.type);
            this.peopleArr = [];
            if (
                this.$route.params.type !== 'BG_LEVEL_KC' &&
                (this.$route.params.type === 'BG_LEVEL_JS' ||
                    this.$route.params.type === 'BG_LEVEL_XS')
            ) {
                this.peopleArr = [getStorage('userInfo')];
                this.formData.username = [getStorage('userInfo').userName];
                getProfessionalById().then(res => {
                    console.log(res, 'changeDept');
                    this.schoolArr = res;
                });
                return;
            }
            if (this.$route.params.type === 'BG_LEVEL_KC') {
                code = this.organizeArr[0].orgCode;
            }
            queryByCode(code).then(res => {
                this.peopleArr = res || [];
                const arr = res.slice(0, 2);
                // console.log(arr, 'arr');
                const defaultProfession = [];
                arr.map(item => defaultProfession.push(item.userName));
                this.formData.username = defaultProfession;
                // console.log(res, 'changeDept', defaultProfession);
            });
        },
        // 根据审核部门查询管理员
        changeAuditDept (val) {
            getUserByDept(val)
                .then(res => {
                    this.deptUserArr = res || [];
                })
                .catch(() => {});
            getAdminAndChargeByOrgId(val)
                .then(res => {
                    if (res) {
                        this.$set(this.formData, 'adminId', res.adminPerson);
                        // console.log(this.formData);
                    }
                })
                .catch(() => {});
        },
        belongDepartment (department) {
            if (department === 'BG_LEVEL_ZY') {
                return '诊改专业';
            }
            if (department === 'BG_LEVEL_KC') {
                return '诊改课程';
            }
            if (department === 'BG_LEVEL_JS' || department === 'BG_LEVEL_XS') {
                return '所属专业';
            }
            return '编制部门';
        }
    }
};
</script>

<style scoped></style>
